package com.yu1996.gulimall.product.service.impl;

import java.math.BigDecimal;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu1996.common.utils.PageUtils;
import com.yu1996.common.utils.Query;

import com.yu1996.gulimall.product.dao.SkuInfoDao;
import com.yu1996.gulimall.product.entity.SkuInfoEntity;
import com.yu1996.gulimall.product.service.SkuInfoService;
import org.springframework.util.StringUtils;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity>
    implements SkuInfoService {



  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<SkuInfoEntity> page =
        this.page(new Query<SkuInfoEntity>().getPage(params), new QueryWrapper<SkuInfoEntity>());

    return new PageUtils(page);
  }

  /**
   * 商品管理的sku条件分页查询
   *
   * @param params
   * @return
   */
  @Override
  public PageUtils queryPageByCondition(Map<String, Object> params) {
    QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<SkuInfoEntity>();
    String key = (String) params.get("key");
    if (!StringUtils.isEmpty(key)) {
      wrapper.and(
          w -> {
            w.like("sku_id", key)
                .or()
                .like("spu_id", key)
                .or()
                .like("sku_name", key)
                .or()
                .like("sku_desc", key);
          });
    }
    String catelogId = (String) params.get("catelogId");
    if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
      wrapper.eq("catalog_id", catelogId);
    }
    String brandId = (String) params.get("brandId");
    if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
      wrapper.eq("brand_id", brandId);
    }
    String min = (String) params.get("min");
    if (!StringUtils.isEmpty(min)) {
      wrapper.ge("price", min);
    }
    String max = (String) params.get("max");
    if (!StringUtils.isEmpty(max)) {
      // 判断价格是否为0 或者输入不合法
      try {
        BigDecimal bigDecimal = new BigDecimal(max);
        if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
          wrapper.le("price", max);
        }
      } catch (Exception e) {

      }
    }
    IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);
    return new PageUtils(page);
  }
  /**
   * 根据spuid查询所有sku
   *
   * @param spuId
   * @return
   */
  @Override
  public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
    return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
  }
}
